#coding=utf-8

from urllib import unquote, urlencode, quote


def filter_query_input(query, scape=True):
    if scape:
        return _safescape(unquote(query))
    return unquote(query)

def _safescape(s):
    """safescape(s) -> htmltext

    Return an 'htmltext' object using the argument.  If the argument is not
    already a 'htmltext' object then the HTML markup characters \", <, >,
    and & are first escaped.

    douban's revision: keep certain tags
    """
    s = s.replace("&", "&#38;") # must be done first
    s = s.replace("<", "&#60;")
    s = s.replace(">", "&#62;")
    s = s.replace('"', "&#34;")
    s = s.replace("'", "&#39;")

    # this is stupid...
    s = s.replace("&lt;br/&gt;", "<br/>")
    return s
